﻿using System;
using UFIDA.U9.CBO.SCM.Item;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;

namespace UFIDA.U9.CusDev.QJKJPlugInBE
{
    class ProcessForPayCompLotNO : IEventSubscriber
    {

        public void Notify(params object[] args)
        {

            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent)) return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;

            if (key == null || key.GetEntity() == null) return;
            //完工报告入库
            UFIDA.U9.MO.Complete.CompleteRptRcvLine rpt = key.GetEntity() as UFIDA.U9.MO.Complete.CompleteRptRcvLine;
            if (rpt == null) return;

            #region 完工报告入库新增时,创建批次号
            //获取该完工报告料品信息
            ItemMaster item = UFIDA.U9.CBO.SCM.Item.ItemMaster.Finder.FindByID(rpt.CompleteRpt.Item.ID);
            if (item == null) return;
            //判断料品下批号参数
            if (item.InventoryInfo.LotParam != null && item.InventoryInfo.LotParam.ID != 0)
            {
                Random rd = new Random();
                int i = rd.Next(1,99);
                String lotcode = rpt.CompleteRpt.ProductLotNo + DateTime.Now.ToString("yyyyMMdd")+i.ToString("00");
                Lot.LotMaster lotMaster = Lot.LotMaster.Finder.Find($"LotCode='{lotcode}'");
                if (lotMaster == null)
                {
                    rpt.RcvLotNo = lotcode;
                   
                        Lot.LotMaster lmaster = Lot.LotMaster.Create();
                        if (rpt.CompleteRpt.ProductLotMaster != null) {
                        using (ISession session = Session.Open())
                        {
                            lmaster.LotCodingRule = rpt.CompleteRpt.ProductLotMaster.LotCodingRule;
                            lmaster.LotCode = lotcode;
                            lmaster.UsingOrg = rpt.CompleteRpt.ProductLotMaster.UsingOrg;
                            lmaster.Name = rpt.CompleteRpt.ProductLotMaster.Name;
                            lmaster.DataOwnerOrg = rpt.CompleteRpt.ProductLotMaster.DataOwnerOrg;
                            lmaster.DocNo = rpt.CompleteRpt.DocNo;
                            //lmaster.Item = rpt.CompleteRpt.Item;
                            session.Commit();
                            rpt.RcvLotMaster = lmaster;
                        }
                    }
                        else
                        {
                            rpt.RcvLotNo = lotcode;
                        }
                }
                else
                {
                    rpt.RcvLotMaster = lotMaster;
                    rpt.RcvLotNo = lotcode;
                }
            }
            else
            {
                return;
            }





            #endregion


        }

    }
}
